package net.towee.model.bittorrent.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.towee.model.bittorrent.Peer;
import net.towee.model.bittorrent.TorrentData;
import net.towee.server.persistence.impl.MongoDbStore;

import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
import com.google.code.morphia.annotations.PostLoad;

/**
 * Implementation of torrent data
 * @author c58
 *
 */
@Entity(MongoDbStore.TORRENTS_COLLECTION)
public class TorrentDataImpl implements TorrentData {
	@Id private String infoHash;
	private Map<String, Peer> peers;
	private int seeds;
	
	public TorrentDataImpl() {}
	public TorrentDataImpl(String infoHash) {
		this.infoHash = infoHash;
		this.peers = new HashMap<String, Peer>();
	}
	
	@PostLoad
	private void createEmptyFields(){
		if(peers == null)
			this.peers = new HashMap<String, Peer>();
	}
	
	@Override
	public String getInfoHash() {
		return infoHash;
	}

	@Override
	public List<Peer> getPeersList() {
		return new ArrayList<Peer>( peers.values() );
	}

	@Override
	public boolean addPeer(Peer pr) {
		if(!peers.containsKey(pr.getId())) { 
			peers.put(pr.getId(), pr); 
			return true;
		}

		return false;
	}

	@Override
	public int getSeeders() {
		return seeds;
	}

	@Override
	public int getLeechers() {
		return peers.size()-seeds;
	}

	@Override
	public void incSeeders() {
		seeds++;
	}

	@Override
	public void decSeeders() {
		seeds--;
	}
	@Override
	public boolean removePeer(String peerId) {
		if(peers.containsKey(peerId)) {
			peers.remove(peerId);
			return true;
		}
		
		return false;
	}
	@Override
	public Peer getPeer(String peerId) {
		return peers.get(peerId);
	}

}
